<script>
import { mapGetters, mapState } from 'vuex'
import { cardStatusArray } from '@/constant/monthCard'
import CardForm from '@/views/car/monthCard/components/cardForm/cardForm.vue'

export default {
  name: 'monthCard',
  components: { CardForm },
  data() {
    return {
      /* 分页和查询月卡的参数 */
      pageParams: {
        // 页数
        page: 1,
        // 条数
        pageSize: 20,
        // 车牌号
        carNumber: undefined,
        // 车主姓名
        personName: undefined,
        // 状态
        cardStatus: null
      },
      /* 待批量删除月卡的ID数组 */
      cardIdList: [],
      /* 状态 */
      cardStatusArray,
      /* 是否处于加载月卡列表的状态 */
      loading: false,
      /* 是否显示抽屉组件 */
      drawer: false,
      // add 添加月卡 edit编辑月卡 renew续费月卡
      controls: ''
    }
  },
  methods: {
    /* 获取月卡列表的回调函数 */
    async fetchCardList() {
      try {
        this.loading = true
        await this.$store.dispatch('monthCard/fetchCardList', this.pageParams)
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    },
    /* 删除月卡列表的回调函数 */
    async deleteCard(id) {
      try {
        const deleteResult = await this.$store.dispatch('monthCard/deleteCard', id)
        this.fetchCardList()
        this.$message.success(deleteResult)
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 获取月卡占有率的回调函数 */
    async fetchProportion() {
      try {
        this.$store.dispatch('monthCard/fetchProportion')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 分页器size发生变化的回调函数 */
    handleSizeChange(pageSize) {
      this.pageParams.pageSize = pageSize
      this.fetchCardList()
    },
    /* 分页器page发生变化的回调函数 */
    handleCurrentChange(page) {
      this.pageParams.page = page
      this.fetchCardList()
    },
    /* 当表格选择项单选框发生变化时会触发该事件 */
    handleSelectionChange(checkedCardList) {
      this.cardIdList = checkedCardList.map(item => item.id)
    },
    /* 格式化状态的回调函数 */
    formatterCardStatus(row, column, cellValue, index) {
      const MAPSTSATUS = {
        0: '可用',
        1: '过期'
      }
      return MAPSTSATUS[row.cardStatus] || '未知状态'
    },
    /* 格式化表格序号的回调函数 */
    indexMethod(index) {
      return (this.pageParams.page - 1) * this.pageParams.pageSize + index + 1
    },
    /* 点击查询按钮的回调函数 */
    handleSearch() {
      this.pageParams.page = 1
      this.fetchCardList()
    },
    /* 点击删除按钮的回调函数 */
    async handleDeleteCard(row) {
      const confirm = await this.$confirm(`此操作将永久删除${row.personName}, 是否继续?`, '提示', { type: 'warning' }).catch(error => error)
      if (confirm === 'cancel') return
      this.deleteCard(row.id)
    },
    /* 点击编辑按钮的回调函数 */
    handleEditCard(row) {
      this.drawer = true
      this.controls = 'edit'
      this.$nextTick(() => {
        this.$refs.cardForm.findCard(row.id)
      })
    },
    /* 点击添加按钮的回调函数 */
    handleAddCard() {
      this.drawer = true
      this.controls = 'add'
    },
    /* 点击续费按钮的回调函数 */
    handleRenew(row) {
      this.drawer = true
      this.controls = 'renew'
      this.$nextTick(() => {
        this.$refs.cardForm.findCard(row.id)
      })
    },
    /* 点击批量删除按钮的回调函数 */
    async handleBatchDeleteCard() {
      if (this.cardIdList.length <= 0) return this.$message.warning('请选择需要批量删除的月卡')
      const confirm = await this.$confirm(`删除选中的月卡, 是否继续?`, '提示', { type: 'warning' }).catch(error => error)
      if (confirm === 'cancel') return

      this.deleteCard(this.cardIdList.join(','))
    },
    /* 子组件添加月卡或者编辑月卡成功的自定义事件 */
    handleSuccess(flag) {
      this.drawer = flag
      this.fetchCardList()
    },
    /* 子组件点击取消按钮的自定义事件 */
    handleCancel(flag) {
      this.drawer = flag
    },
    /* 抽屉组件被关闭时候的回调函数 */
    handleCloseDrawer() {
      this.$refs.cardForm.handleReset()
    }
  },
  computed: {
    ...mapState('monthCard', ['proportion']),
    ...mapGetters('monthCard', ['cardList', 'total']),
    alertTitle() {
      return `本园区共计${this.proportion.spaceNumber || 0}个车位，月卡用户${this.proportion.cardCount || 0}人，车位占有率${this.proportion.proportion || 0}`
    },
    drawerTitle() {
      let title = ''
      if (this.controls === 'add') {
        title = '添加月卡'
      } else if (this.controls === 'edit') {
        title = '编辑月卡'
      } else {
        title = '续费月卡'
      }
      return title
    }
  },

  created() {
    this.fetchCardList()
    this.fetchProportion()
  }
}
</script>

<template>
  <div class="monthCard">
    <el-card>
      <el-form inline>
        <el-form-item label="车牌号码">
          <el-input size="small" placeholder="请输入车牌号码" v-model="pageParams.carNumber"></el-input>
        </el-form-item>
        <el-form-item label="车主姓名">
          <el-input size="small" placeholder="请输入车主姓名" v-model="pageParams.personName"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select size="small" placeholder="请选择状态" v-model="pageParams.cardStatus">
            <el-option v-for="(item) in cardStatusArray" :value="item.value" :label="item.label" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <el-button size="small" type="success" icon="el-icon-plus" @click="handleAddCard">添加月卡</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" @click="handleBatchDeleteCard">批量删除</el-button>
        </el-col>
        <el-col :span="6">
          <el-alert :title="alertTitle" type="info" show-icon :closable="false"></el-alert>
        </el-col>
      </el-row>
      <el-table border stripe size="small" :data="cardList" v-loading="loading" element-loading-text="拼命加载中" :header-cell-style="{background:'#4d8ed9',color:'#fff'}" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column type="index" :index="indexMethod" label="序号" align="center"></el-table-column>
        <el-table-column label="车主名称" align="center" prop="personName"></el-table-column>
        <el-table-column label="联系方式" align="center" prop="phoneNumber"></el-table-column>
        <el-table-column label="车牌号码" align="center" prop="carNumber"></el-table-column>
        <el-table-column label="车辆品牌" align="center" prop="carBrand"></el-table-column>
        <el-table-column label="剩余有效天数" align="center" prop="totalEffectiveDate"></el-table-column>
        <el-table-column label="状态" align="center" :formatter="formatterCardStatus"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="text" @click="handleRenew(row)">续费</el-button>
            <el-button type="text">查看</el-button>
            <el-button type="text" @click="handleEditCard(row)">编辑</el-button>
            <el-button type="text" @click="handleDeleteCard(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParams.page"
        :page-sizes="[ 20, 30, 40,50]"
        :page-size="pageParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>
    <el-drawer :title="drawerTitle" :visible.sync="drawer" :wrapperClosable="false" @close="handleCloseDrawer">
      <card-form ref="cardForm" @success="handleSuccess" @cancel="handleCancel" :controls="controls"></card-form>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.monthCard {
  .el-card {
    margin-bottom: 10px;

    .el-form-item {
      margin-bottom: unset;
    }

    .el-select {
      width: 100% !important;
    }
  }

  .el-table {
    margin: 10px 0;
  }

  .el-pagination {
    display: flex;
    justify-content: center;
  }
}
</style>
